package com.bardsoftware.foronuvolo.server;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.compass.core.Compass;
import org.compass.core.CompassIndexSession;

import com.bardsoftware.foronuvolo.data.Discussion;
import com.bardsoftware.foronuvolo.data.DatastoreDiscussionChunk;
import com.bardsoftware.foronuvolo.data.DiscussionChunk;
import com.bardsoftware.foronuvolo.data.Message;
import com.bardsoftware.foronuvolo.data.PMF;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskHandle;
import com.google.appengine.api.labs.taskqueue.TaskOptions;

public class IndexServlet extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(IndexServlet.class.getName());
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        LOGGER.warning("IndexServlet");
        if (!req.getRequestURL().toString().startsWith(ForoNuvoloConstants.FORUM_DOMAIN)) {
            return;
        }
        final String startParam = req.getParameter("start");
        final DiscussionChunk chunk = startParam == null ?
                DatastoreDiscussionChunk.getFirstPage() : DatastoreDiscussionChunk.getPage(startParam);
        String nonextParam = req.getParameter("nonext");
        final boolean noNext = "true".equalsIgnoreCase(nonextParam);

        final String countParam = req.getParameter("count");
        LOGGER.warning(chunk.toString());
        PMF.runInTransaction(null, new Runnable() {
            public void run() {
                int count = countParam == null ? -1 : Integer.valueOf(countParam).intValue();
                Compass c = PMF.getCompass();
                c.getSearchEngineIndexManager().releaseLocks();
                CompassIndexSession indexSession = c.openIndexSession();
                for (Discussion d: chunk.getDiscussions()) {
                    LOGGER.warning("saving discussion="+d.getIndexableContent());
                    indexSession.save(d);
                    if (--count == 0) {
                        break;
                    }
                }
                indexSession.commit();
                indexSession.close();
                if (!noNext && !"".equals(chunk.getNextChunkID())) {
                    TaskOptions options = TaskOptions.Builder.url("/index").param("start", chunk.getNextChunkID()).method(TaskOptions.Method.GET);
                    TaskHandle add = QueueFactory.getDefaultQueue().add(options);
                }
            }

        }, 3);
    }

}
